package com.umpay.config;

import java.util.Properties;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
/**
 * 
<p>Title:DynamicDataSourceInterceptor</p>  
<p>Description: mybatis的拦截器，对读写方法拦截，根据线程变量切换本地线程状态获取不同数据源</p>
<p>Company: UMPAY</p>
 @author lifeng
 @date 2018年1月17日
 */
@Intercepts({
		@Signature(type = Executor.class, method = "update", args = {
				MappedStatement.class, Object.class }),
		@Signature(type = Executor.class, method = "query", args = {
				MappedStatement.class, Object.class, RowBounds.class,
				ResultHandler.class}),
		@Signature(type = Executor.class, method = "query", args = {
			MappedStatement.class, Object.class, RowBounds.class,
			ResultHandler.class,CacheKey.class,BoundSql.class })})
public class DynamicDataSourceInterceptor implements Interceptor {

	public Object intercept(Invocation paramInvocation) throws Throwable {
		MappedStatement mappedStatement = (MappedStatement) paramInvocation
				.getArgs()[0];
		if(mappedStatement.getId().lastIndexOf("OffDao") > 0){
			DatabaseContextHolder.setDatabaseType(DatabaseType.offlineDB);
		}else{
			DatabaseContextHolder.setDatabaseType(DatabaseType.onlineDB);
		}
		return paramInvocation.proceed();
	}

	public Object plugin(Object paramObject) {
		return Plugin.wrap(paramObject, this);
	}

	public void setProperties(Properties paramProperties) {

	}

}
